package acn.spring.backend.springDataJpa;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import acn.spring.domain.Category;
import acn.spring.domain.Product;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

	List<Product> findByName(String name);

	Page<Product> findByCategory(Category category, Pageable pageable);

	List<Product> findByNameAndCategory(String name, Category category);

	// @formatter:off
	@Query(value = "select top 5 p.*, sum(po.quantity) as total_quantity from product p " +
			"inner join productorder po " +
            	"on p.id = po.product_id " +
            "group by p.id, p.name " +
			"order by total_quantity desc", nativeQuery = true)
	List<Product> findTopFiveBestSeller();
    
    @Query(value = "select p, sum(po.quantity) as total_quantity " + 
            "from ProductOrder po " +
            "right join po.pk.product p where p.category = (?1) " +
            "group by p.id, p.name " +
            "order by total_quantity desc nulls last")
    Page<Object[]> findBestSellerProductsByCategory(Category category, Pageable pageable);
	// @formatter:on

}